<?php

	namespace org\tekuna\framework;

	use org\tekuna\base\Tekuna;
	
	use org\tekuna\core\event\Event;
	use org\tekuna\core\event\AbstractEventListener;
	
	use org\tekuna\framework\response\ResponseEvent;
	use org\tekuna\framework\response\BeforeResponseSendEvent;
	use org\tekuna\framework\response\AfterResponseSendEvent;
	use org\tekuna\framework\response\http\AbstractHttpResponse;
	use org\tekuna\framework\response\http\ContentResponse;
	use org\tekuna\framework\info\InformationEvent;
	

	class ResponseListener extends AbstractEventListener {

		protected $objResponse = NULL;
		
		
		public function handlesEvent(Event $objEvent) {
			
			return ($objEvent instanceof ResponseEvent) || ($objEvent instanceof InformationEvent);
		}
		
		public function handleEvent(Event $objEvent) {

			if ($objEvent instanceof ResponseEvent) {
				
				$this -> objResponse = $objEvent -> getResponse();
				$objEventManager = $this -> getApplicationContext() -> getEventManager();
				
				// send before event
				$objEventManager -> triggerEvent(new BeforeResponseSendEvent($this -> objResponse));
				
				// send the actual response
				$this -> objResponse -> sendResponse();
				
				// send before event
				$objEventManager -> triggerEvent(new AfterResponseSendEvent($this -> objResponse));
			}
			
			if ($objEvent instanceof InformationEvent && $this -> objResponse != null) {
				
				$this -> provideResponseInformation($objEvent);
			}
		}
		
		
		private function provideResponseInformation(InformationEvent $objEvent) {
			
			$sOutput = '';
			$sOutput .= "Note: all values without consideration of the information output:\n\n";
			$sOutput .= 'Response Class: '. get_class($this -> objResponse) ."\n";
			
			if ($this -> objResponse instanceof AbstractHttpResponse) {
				
				$sOutput .= 'Protocol: '. $this -> objResponse -> getProtocol() .' '. $this -> objResponse -> getProtocol() .' '. $this -> objResponse -> getStatusMessage($this -> objResponse -> getStatus()) ."\n";
				$sOutput .= 'Status: '. $this -> objResponse -> getProtocol() .' '. $this -> objResponse -> getStatus() .' '. $this -> objResponse -> getStatusMessage($this -> objResponse -> getStatus()) ."\n";
			}
			
			if ($this -> objResponse instanceof ContentResponse) {
				
				$sOutput .= 'Content Type: '. $this -> objResponse -> getContentType() ."\n";
				$sOutput .= 'Character Set: '. $this -> objResponse -> getCharset() ."\n";
				$sOutput .= 'Output Compression: '. ($this -> objResponse -> isCompressOutput() ? 'ENABLED' : 'DISABLED') ."\n";
				$sOutput .= 'Content Size: '. strlen($this -> objResponse -> getContent()) ." Bytes\n";
			}
			
			$objEvent -> addInfoSection('Response', $sOutput);
		}
	}